package com.mapbased.sfw.model;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.mapbased.sfw.store.PathData;

public class GeneralEnum implements java.io.Externalizable{
	
	EnumType type=EnumType.ALone;

	public String name;
	public String caption="";

	public final List<EnumItem> items = new CopyOnWriteArrayList<EnumItem>();

	public GeneralEnum(PathData pd) {
		 
		java.io.ByteArrayInputStream bis=new ByteArrayInputStream(pd.value);
		java.io.ObjectInputStream ois=null;
		try {
			ois = new java.io.ObjectInputStream(bis);
			this.readExternal(ois);
		} catch ( Exception e) {

				throw new java.lang.RuntimeException(e);
		}
		finally{
			if(ois!=null){
				try {
					ois.close();
				} catch (IOException e) {
					 
				}
			}
		}
		 
	}

	public GeneralEnum() {

	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		 this.caption= in.readUTF();
		 int o=in.readInt();
		 this.type=EnumType.values()[o];
		 int cnt=in.readInt();
	
		List<EnumItem> al = new java.util.ArrayList<EnumItem>(cnt);
		 for(int i=0;i<cnt;i++){
			 EnumItem e=new EnumItem();
			e.readExternal(in);
			al.add(e);
		 }
		 items.addAll(al);
		
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		 out.writeUTF(this.caption);
		 out.writeInt(this.type.ordinal());
		 EnumItem[] is=items.toArray(new EnumItem[items.size()]); 
		 out.writeInt(is.length);
		 for(EnumItem e :is){
			 e.writeExternal(out);
		 }
		 
		
	}


}
